package capricornus.components.utils.fadeaway
{
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.Regular;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.EventDispatcher;

	[Event(name="motionFinish", type="fl.transitions.TweenEvent")]
	public class FadeAwayController extends EventDispatcher
	{
		private var tween:Tween;
		private var target:DisplayObject = null;
		private var oldAlpha:Number = 1;
		private var fadeAndRemoved:Boolean = false;
		
		private var duration:Number;
		private var resetOnFinish:Boolean;
		
		public function FadeAwayController( duration:Number = 0.2, resetOnFinish:Boolean=true, fadeAndRemoved:Boolean=false )
		{
			this.duration = duration;
			this.resetOnFinish = resetOnFinish;
			this.fadeAndRemoved = fadeAndRemoved;
			
			init();
		}
		
		public function init():void
		{
			tween = new Tween( this, "change", Regular.easeOut, 0, 1, duration, true );
			tween.stop();
			tween.addEventListener( TweenEvent.MOTION_FINISH, onMotionFinish, false, 0, true );
		}
		
		public function destroy():void
		{
			tween.removeEventListener( TweenEvent.MOTION_FINISH, onMotionFinish );
			tween = null;
			target = null;
		}
		
		public function set change( value:Number ):void
		{
			if( tween != null && tween.isPlaying )
			{
				if( target != null )
				{
					target.alpha = value;
				}
			}
		}
		
		public function get currentTarget():DisplayObject
		{
			return target;
		}
		
		public function stop():void
		{
			target = null;
			tween.stop();
		}
		
		public function finishAtOnce():void
		{
			onMotionFinish( null );
		}
		
		private function onMotionFinish( e:TweenEvent ):void
		{
			if( target==null ) return;
			
			if( resetOnFinish ) target.alpha = oldAlpha;
			if( fadeAndRemoved )
			{
				if( target.parent != null )
				{
					target.parent.removeChild( target );
				}
			}
			target = null;
			
			this.dispatchEvent( new TweenEvent( TweenEvent.MOTION_FINISH, 0, 0 ) );
		}
		
		public function fade( target:DisplayObject, fadeAndRemoved:Boolean=true ):void
		{
			onMotionFinish( null );
			
			oldAlpha = target.alpha;
			this.fadeAndRemoved = fadeAndRemoved;
			this.target = target;
			
			tween.begin = 1;
			tween.finish = 0;
			tween.start();
		}
		
		public function show( target:DisplayObject ):void
		{
			onMotionFinish( null );
			
			oldAlpha = target.alpha;
			this.target = target;
			fadeAndRemoved = false;
			
			target.alpha = 0;
			tween.begin = 0;
			tween.finish = 1;
			tween.start();
		}
	}
}




